package com.util.alicloud.alipay;

import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.bean.yxy.AlipayBean;
import com.bean.yxy.config.AliPayConfig;

import java.util.Date;
import java.util.UUID;

public class AliPay {
    /**
     * 支付接口
     * @param alipayBean
     * @return
     * @throws AlipayApiException
     */
    public String pay(AlipayBean alipayBean) throws AlipayApiException {
        // 1、获得初始化的AlipayClient
        String serverUrl = AliPayConfig.OPEN_API_DOMAIN;
        String appId = AliPayConfig.APPID;
        String privateKey = AliPayConfig.PRIVATE_KEY;
        String format = "json";
        String charset = "utf-8";
        String alipayPublicKey =AliPayConfig.ALIPAY_PUBLIC_KEY;
        String signType = AliPayConfig.SIGN_TYPE;
        String returnUrl = AliPayConfig.RETURN_URL;
        String notifyUrl = AliPayConfig.RETURN_URL;
        AlipayClient alipayClient = new DefaultAlipayClient(serverUrl, appId, privateKey, format, charset, alipayPublicKey, signType);
        // 2、设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        // 页面跳转同步通知页面路径
        alipayRequest.setReturnUrl(returnUrl);
        // 服务器异步通知页面路径
        alipayRequest.setNotifyUrl(notifyUrl);
        //账户订单号
        String out_trade_no = new Date().getTime()+ UUID.randomUUID().toString();
        alipayBean.setOut_trade_no(out_trade_no);
        // 封装参数
        alipayRequest.setBizContent(JSON.toJSONString(alipayBean));
        // 3、请求支付宝进行付款，并获取支付结果
        String result = alipayClient.pageExecute(alipayRequest).getBody();
        // 返回付款信息
        return result;
    }
}

